<template>
  <div>
    <!-- 使用原有的顶部导航栏组件 -->
    <AppHeader :user="userStore.user" />

    <div class="main-container">
      <!-- 工具栏 -->
      <div class="toolbar">
        <div class="role-nav">
          <button
            v-for="(role, index) in roles"
            :key="index"
            :class="['btn', currentRole === role ? 'btn-active' : '']"
            @click="updateRole(role)"
          >
            {{ role }}
          </button>
        </div>

        <div class="button-group">
          <button
            v-if="['我是老师', '我是助教'].includes(currentRole)"
            class="create-btn"
            @click="goToCreateCourse"
          >
            <i class="bi bi-plus-circle me-2" />创建课程
          </button>
          <button
            v-if="currentRole === '我是学生'"
            class="join-btn"
            @click="goToJoinCourse"
          >
            <i class="bi bi-link-45deg me-2" />加入课程
          </button>
        </div>
      </div>

      <!-- 加载状态 -->
      <div
        v-if="isLoading"
        class="loading-state"
      >
        <div
          class="spinner-border text-primary"
          role="status"
        />
        <span class="ms-3">加载课程中...</span>
      </div>

      <!-- 课程列表 -->
      <div class="course-list-container">
        <div
          v-for="(course, index) in currentCourses"
          :key="index"
          class="course-card"
        >
          <img
            :src="course.imageUrl || DEFAULT_IMAGE_URL"
            alt="课程图片"
            class="course-image"
          >
          <div class="course-info">
            <h3 class="course-name">
              {{ course.courseName }}
            </h3>
            <p class="course-code">
              课程编号：{{ course.courseId }}
            </p>
            <button
              class="enter-btn"
              @click="enterCourse(course)"
            >
              <i class="bi bi-door-open me-2" />进入课程
            </button>
          </div>
        </div>

        <!-- 无课程提示 -->
        <div
          v-if="!isLoading && currentCourses.length === 0"
          class="empty-state"
        >
          <div class="empty-state-icon">
            <i class="bi bi-book" />
          </div>
          <h3>暂无课程</h3>
          <p>您尚未创建或加入任何课程，点击上面的按钮开始吧</p>
        </div>
      </div>
    </div>
  </div>
  <FooterComponent />
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/userStore';
import AppHeader from '@/components/main_page/AppHeader.vue'; // 导入原始的AppHeader组件
import FooterComponent from "@/components/UserCenter/FooterComponent.vue";
// 注意：courseAPI会在fetchCourses函数中动态导入，避免循环依赖

const router = useRouter();
const userStore = useUserStore();

const DEFAULT_IMAGE_URL = 'https://spoc.buaa.edu.cn/inco-filesystem/fileManagerSystem/getFileStream?scjlid=1981389556AF1337E0630211FE0A6CEE';

// 角色映射表：中文 → 英文标识
const roleMap = {
  '我是老师': 'Teacher',
  '我是助教': 'Teaching_Assistant',
  '我是学生': 'Student'
};

// 角色列表
const roles = ref(['我是老师', '我是助教', '我是学生']);

// 当前选中的角色
const currentRole = ref(roles.value[0]);

// 存储从后端获取的所有课程数据
const courses = ref([]);

// 加载状态
const isLoading = ref(false);

// 根据当前角色过滤课程
const currentCourses = computed(() => {
  return courses.value;
});

// 进入课程逻辑
const enterCourse = (course) => {
  router.push(`/course/${course.courseId}`);
};

// 获取课程数据
const fetchCourses = async () => {
  isLoading.value = true;

  const backendRole = roleMap[currentRole.value];
  if (!backendRole) {
    isLoading.value = false;
    return;
  }

  const userId = userStore.user?.userId || '';

  if (!userId) {
    isLoading.value = false;
    return;
  }

  try {
    // 导入并使用courseAPI
    const { courseAPI } = await import('@/api/course.js');
    const response = await courseAPI.getUserCourses(userId, backendRole);
    console.log('获取课程响应:', response);
    
    // 确保正确处理响应数据结构
    const coursesData = response.data?.data || [];
    courses.value = coursesData.map(course => ({
      ...course,
      // 确保每个课程都有图片URL
      imageUrl: course.imageUrl || DEFAULT_IMAGE_URL
    }));
  } catch (error) {
    console.error('获取课程失败:', error);
    // 在实际应用中可以根据错误状态处理不同的错误情况
    if (error.response?.status === 401) {
      router.push('/login');
    }
  } finally {
    isLoading.value = false;
  }
};

// 角色变化时重新获取数据
const updateRole = async (newRole) => {
  currentRole.value = newRole;
  await fetchCourses();
};

// 创建课程
const goToCreateCourse = () => {
  router.push('/create-course');
};

// 加入课程
const goToJoinCourse = () => {
  router.push('/join-course');
};

// 页面加载时获取数据
onMounted(async () => {
  if (!userStore.user) {
    router.push('/login');
    return;
  }

  await fetchCourses();
});
</script>

<style>
:root {
  --primary-color: #4A90E2;     /* 主色调 - 蓝色 */
  --primary-light: #E7F0FA;    /* 浅蓝色 */
  --primary-dark: #2d70c4;     /* 深蓝色 */
  --success-color: #52C41A;    /* 成功色 - 绿色 */
  --success-light: #EDF7E8;    /* 浅绿色 */
  --info-color: #1890FF;       /* 信息色 - 天蓝色 */
  --white-color: #FFFFFF;      /* 白色 */
  --light-grey: #F7F9FC;       /* 背景浅灰色 */
  --mid-grey: #E5E8F0;        /* 中等灰色 */
  --text-primary: #2D3748;     /* 主要文本色 */
  --text-secondary: #718096;   /* 次要文本色 */
  --text-light: #A0AEC0;       /* 浅色文本 */
  --card-radius: 16px;         /* 卡片圆角 */
  --shadow-light: 0 4px 12px rgba(0, 0, 0, 0.05);
  --hover-shadow: 0 8px 16px rgba(0, 0, 0, 0.08);
  --header-height: 68px;
  --transition: all 0.3s ease;
}

.main-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 32px;
  padding-top: 80px; /* 为导航栏留出空间 */
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 24px;
  margin-bottom: 32px;
  padding: 24px;
  background: var(--white-color);
  border-radius: var(--card-radius);
  box-shadow: var(--shadow-light);
}

/* 角色导航美化 */
.role-nav {
  display: flex;
  background: var(--white-color);
  border-radius: 30px;
  padding: 4px;
  box-shadow: var(--shadow-light);
  flex-wrap: wrap;
}

.role-nav .btn {
  padding: 10px 28px;
  border-radius: 26px;
  border: none;
  font-weight: 600;
  transition: var(--transition);
  background: transparent;
  color: var(--text-secondary);
  box-shadow: none !important;
}

.role-nav .btn:hover {
  background-color: var(--primary-light);
  color: var(--primary-color);
}

.role-nav .btn.btn-active {
  background-color: var(--primary-color);
  color: var(--white-color);
  box-shadow: 0 4px 8px rgba(74, 144, 226, 0.25) !important;
}

/* 按钮样式 */
.button-group {
  display: flex;
  gap: 12px;
}

.create-btn, .join-btn {
  padding: 10px 24px;
  border-radius: 30px;
  font-weight: 600;
  transition: var(--transition);
  border: none;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  cursor: pointer;
  white-space: nowrap;
}

.create-btn {
  background: linear-gradient(135deg, var(--success-color), #66bb6a);
  color: var(--white-color);
}

.create-btn:hover {
  background: linear-gradient(135deg, #3b9412, #58a35e);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(82, 196, 26, 0.3);
}

.join-btn {
  background: linear-gradient(135deg, var(--primary-dark), var(--primary-color));
  color: var(--white-color);
}

.join-btn:hover {
  background: linear-gradient(135deg, #075bc0, #3d85d6);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(24, 144, 255, 0.3);
}

/* 课程列表 */
.course-list-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}

/* 课程卡片样式 */
.course-card {
  background-color: var(--white-color);
  border-radius: var(--card-radius);
  overflow: hidden;
  transition: var(--transition);
  box-shadow: var(--shadow-light);
  display: flex;
  flex-direction: column;
  height: 100%;
}

.course-card:hover {
  transform: translateY(-8px);
  box-shadow: var(--hover-shadow);
}

.course-image {
  width: 100%;
  height: 160px;
  object-fit: cover;
  background: linear-gradient(45deg, #e6f7ff, #d5f5f6);
  border-bottom: 1px solid var(--mid-grey);
  position: relative;
  overflow: hidden;
}

.course-image::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,0.5));
}

.course-info {
  padding: 20px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.course-name {
  font-size: 1.1rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 12px;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  min-height: 42px;
}

.course-code {
  font-size: 0.85rem;
  color: var(--text-light);
  margin-bottom: 16px;
}

.enter-btn {
  background: linear-gradient(to right, var(--primary-dark), var(--primary-color));
  color: var(--white-color);
  font-weight: 600;
  padding: 10px 16px;
  border-radius: 8px;
  border: none;
  text-decoration: none;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: auto;
  transition: var(--transition);
  cursor: pointer;
}

.enter-btn:hover {
  background: linear-gradient(to right, #2560b4, #4280d0);
  transform: scale(1.02);
}

/* 加载状态 */
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 80px;
  background: var(--white-color);
  border-radius: var(--card-radius);
  box-shadow: var(--shadow-light);
  font-size: 1.1rem;
  color: var(--text-light);
}

/* 无课程提示 */
.empty-state {
  background: var(--white-color);
  border-radius: var(--card-radius);
  box-shadow: var(--shadow-light);
  padding: 48px 24px;
  text-align: center;
  grid-column: 1 / -1;
}

.empty-state-icon {
  font-size: 5rem;
  color: var(--primary-light);
  margin-bottom: 20px;
  opacity: 0.7;
}

.empty-state h3 {
  margin-bottom: 16px;
  color: var(--text-primary);
}

.empty-state p {
  color: var(--text-light);
  margin-bottom: 24px;
  max-width: 500px;
  margin-left: auto;
  margin-right: auto;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .role-nav {
    justify-content: center;
  }

  .button-group {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .main-container {
    padding: 16px;
    padding-top: 70px; /* 为导航栏留出空间 */
  }

  .toolbar {
    margin-top: 16px;
    padding: 16px;
  }

  .role-nav .btn {
    padding: 8px 16px;
    font-size: 0.9rem;
    margin-bottom: 4px;
  }
}

@media (max-width: 480px) {
  .role-nav .btn {
    padding: 6px 12px;
    font-size: 0.85rem;
  }

  .create-btn, .join-btn {
    padding: 8px 16px;
    font-size: 0.9rem;
  }

  .course-list-container {
    grid-template-columns: 1fr;
  }
}
</style>

